<template>
  <a-modal
    title="批量添加"
    v-model:open="open"
    width="80%"
    @ok="confirm"
    :ok-button-props="{
      disabled: repeat == 0,
    }"
  >
    <div>
      <div flex-center gap-2>
        <a-tooltip title="添加前缀">
          <a-button type="link" @click="openPrefix">+</a-button>
        </a-tooltip>

        <a-tag
          @click="editItem(item)"
          v-for="(item, i) in prefixList"
          :key="i"
          closable
          @close.prevent="removeItem(prefixList, i)"
          size="large"
          h-32px
          leading-30px
          color="#87d068"
        >
          {{ convert(item) }}
        </a-tag>

        <a-input
          :maxlength="20"
          max-w-200px
          placeholder="请输入文本"
          v-model:value="text"
        ></a-input>

        <a-tag
          @click="editItem(item)"
          v-for="(item, i) in suffixList"
          :key="i"
          closable
          @close.prevent="removeItem(suffixList, i)"
          size="large"
          h-32px
          leading-30px
          color="#2db7f5"
        >
          {{ convert(item) }}
        </a-tag>

        <a-tooltip title="添加后缀">
          <a-button type="link" @click="openSuffix">+</a-button>
        </a-tooltip>
        <div>重复次数</div>
        <a-input-number
          v-model:value="repeat"
          placehoder="重复次数"
          :min="0"
        ></a-input-number>
      </div>

      <a-list :data-source="list" class="max-h-500px" overflow-y-auto>
        <template #renderItem="{ item }">
          <a-list-item>
            <div truncate>
              {{ item }}
            </div>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </a-modal>
  <a-modal
    :title="title"
    v-model:open="showAddon"
    @ok="handleOk"
    destroy-on-close
  >
    <a-form
      :label-col="{ span: 4 }"
      :model="form"
      :rules="formRules"
      ref="formRef"
    >
      <a-form-item label="类型">
        <a-radio-group v-model:value="form.type">
          <a-radio value="count">数字</a-radio>
          <a-radio value="text">文本</a-radio>
        </a-radio-group>
      </a-form-item>

      <template v-if="form.type == 'count'">
        <a-form-item label="初始值" name="init">
          <a-input-number
            class="w-full!"
            v-model:value="form.init"
            placeholder="请输入初始值"
          ></a-input-number>
        </a-form-item>

        <a-form-item label="步长" name="step">
          <a-input-number
            class="w-full!"
            v-model:value="form.step"
            placeholder="请输入步长"
          ></a-input-number>
        </a-form-item>
      </template>

      <template v-if="form.type == 'text'">
        <a-form-item label="文本" name="value">
          <a-input
            :maxlength="20"
            placeholder="请输入文本"
            v-model:value="form.value"
          ></a-input>
        </a-form-item>
      </template>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { FormInstance } from 'ant-design-vue';

type PrefixNumber = {
  type: 'count';
  init: number;
  step: number;
};

type PrefixLetter = {
  type: 'text';
  value: string;
};

type Prefix = PrefixNumber | PrefixLetter;

const open = ref(false);

const text = ref('');

const repeat = ref(1);

const callback = ref(() => {});

const title = ref('');
const showAddon = ref(false);
const form = ref({} as Prefix);
const formRules = computed((): Record<string, any> => {
  if (form.value.type == 'count') {
    return {
      init: [{ required: true, message: '请输入' }],
      step: [{ required: true, message: '请输入' }],
    };
  } else {
    return {
      value: [{ required: true, message: '请输入' }],
    };
  }
});

const formRef = ref<FormInstance>();

const convert = (value: Prefix) => {
  if (value.type == 'count') {
    const { init, step } = value;
    return `${init}/${step}`;
  } else {
    return value.value;
  }
};

const prefixList = ref<Prefix[]>([]);
const suffixList = ref<Prefix[]>([]);

const openPrefix = () => {
  form.value = {
    type: 'count',
    step: 1,
    init: 1,
  };
  title.value = '添加前缀';
  showAddon.value = true;
  callback.value = () => {
    prefixList.value.unshift(cloneDeep(form.value));
  };
};

const openSuffix = () => {
  form.value = {
    type: 'count',
    step: 1,
    init: 1,
  };
  title.value = '添加后缀';
  form.value.type = 'count';
  showAddon.value = true;
  callback.value = () => {
    suffixList.value.push(cloneDeep(form.value));
  };
};

const editItem = (item: Prefix) => {
  form.value = cloneDeep(item);
  title.value = '编辑';
  showAddon.value = true;
  callback.value = () => {
    Object.entries(form.value).forEach(record => {
      const [key, val] = record;
      item[key] = val;
    });
  };
};

const removeItem = (list: Prefix[], idx: number) => {
  list.splice(idx, 1);
};

const handleOk = () => {
  formRef.value?.validate().then(() => {
    callback.value();
    showAddon.value = false;
  });
};

const list = computed(() => {
  const arr: string[] = [];

  const getAddonValue = (list: Prefix[], i: number) => {
    return list
      .map(item => {
        if (item.type == 'count') {
          return item.init + i * item.step;
        } else {
          return item.value;
        }
      })
      .join('');
  };

  for (let i = 0; i < repeat.value; i++) {
    const prefix = getAddonValue(prefixList.value, i);
    const suffix = getAddonValue(suffixList.value, i);
    arr.push(`${prefix}${text.value}${suffix}`);
  }

  return arr;
});

const confirmCb = ref<(list: string[]) => boolean>();

const confirm = () => {
  const hasCount = [...suffixList.value, ...prefixList.value].some(
    item => item.type === 'count',
  );
  if (!hasCount) {
    message.error('至少要有一个数字类型的前缀或后缀,否则数据重复');
    return;
  }
  const res = confirmCb.value?.(list.value);
  open.value = !res;
};

const show = (cb: (list: string[]) => boolean) => {
  confirmCb.value = cb;
  suffixList.value = [];
  prefixList.value = [];
  repeat.value = 1;
  text.value = '';
  open.value = true;
};

defineExpose({
  show,
});
</script>
